// $_FILEHEADER_BEGIN ***************************
// 版权声明:北京畅聊天下科技有限公司版权所有
// Copyright © 2012 - Changliao Technology Co.Ltd. All Rights Reserved
// 文件名称: BarrageView.m
// 创建日期: 16/1/24
// 创 建 人: 甄鑫
// 文件说明: <#content#>
// $_FILEHEADER_END ******************************


#import "BarrageView.h"
#import "SDWebImageManager.h"
#import "UIView+UIView_ITAdditions.h"


@implementation BarrageView
{
    UIView * _contentView;

    NSMutableArray<ItemView *> * _brrageItemArr;
}
-(void)dealloc{
    
}
- (void)playAnimation{

    NSAssert(_playTime != 0, @"动画时间为0");
    NSAssert(_brrageItemArr.count != 0, @"没有弹幕视图");
    
    if (_playTime == 0 || _brrageItemArr.count == 0) {
        ITLog(@"动画时间为0 或者 没有弹幕视图");
        return;
    }
    
    for (ItemView * itemViewItem in _brrageItemArr) {
        [itemViewItem setFrame_x:self.width];
        [itemViewItem setFrame_y:[self getAReadomY]];
        [UIView animateWithDuration:[itemViewItem playTime]
                              delay:[self getAReadomPlayBeignTime]
                            options:UIViewAnimationOptionCurveLinear
                         animations:^{
            [itemViewItem setFrame_x:-itemViewItem.width-SCREEN_WIDTH];
        } completion:^(BOOL finished) {
            
        }];
    }
    @weakify(self);
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_playTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        @strongify(self);
        if (!self) {
            return ;
        }
        [self playAnimation];
    });
}

- (CGFloat)getAReadomY{
    NSInteger viewH = self.height;
    return arc4random()%viewH;
}

- (CGFloat)getAReadomPlayBeignTime{
    return arc4random()%((NSInteger)_playTime);
}

-(void)setBrrageDataArr:(ItemModelArr *)brrageDataArr{
    _brrageDataArr = brrageDataArr;
    
    if (!_contentView) {
        _contentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.width, self.height)];
        [_contentView setBackgroundColor:[UIColor clearColor]];
        [self addSubview:_contentView];
    }
    if(!_brrageItemArr){
        _brrageItemArr = [[NSMutableArray alloc]init];
    }
        
    NSInteger itemCount = [_brrageDataArr count];
    CGFloat itemPlayTime = _playTime /itemCount;
    
    for (ItemModel dataModelItem in _brrageDataArr) {
        Class<BarrageItemViewProtocol> itemViewClass = [dataModelItem viewClass];
        ItemView * itemV = [itemViewClass create];
        [itemV setItemModel:dataModelItem];
        if ([dataModelItem playTime]==0) {
            [itemV setPlayTime:itemPlayTime];
        }else{
            [itemV setPlayTime:[dataModelItem playTime]];
        }
        [_brrageItemArr addObject:itemV];
        [_contentView addSubview:itemV];
    }
}
@end
